import sys
import cgi
import string
import wsgiref.handlers
from datetime import datetime
import rfc822
import json

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.api import users

import html
import tweet
import appconfig
import minicloud

# Index
class IndexHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(html.header())
        self.response.out.write(html.about())
        self.response.out.write(html.footer())

# Load Config Form
class LoadConfigHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(html.header())
        self.response.out.write(html.config_form())
        self.response.out.write(html.footer())


# Save Config Form
class SaveConfigHandler(webapp.RequestHandler):
    def post(self):
        cfg = { 
                'twitter_username' : self.request.get('twitter_username'),
                'twitter_password' : self.request.get('twitter_password'),
                'twitter_url' : self.request.get('twitter_url'),
                'minicloud_username' : self.request.get('minicloud_username'),
                'minicloud_password' : self.request.get('minicloud_password'),
                'minicloud_url' : self.request.get('minicloud_url')
               }
        appconfig.set_all(cfg)
        self.response.out.write(html.header())
        self.response.out.write("Configuration has been saved successfully!")
        self.response.out.write(html.footer())


# Fetch Top 20 tweet
class TwitterHandler(webapp.RequestHandler):
    def get(self):
        try:
            tweets = tweet.fetch()
            self.response.out.write(html.tweets(tweets))
        except urlfetch.Error, e:
            msg = str(e) + "<br>Your twitter url is: " + appconfig.get_param("twitter_url")
            self.response.out.write(html.error(msg))



# Input minicloud text
class MinicloudHandler(webapp.RequestHandler):
    def get(self): 
        self.response.out.write(html.header()) 
        self.response.out.write(html.minicloud()) 
        self.response.out.write(html.footer())


# Post text to minicloud
class UpdateHandler(webapp.RequestHandler):
    def post(self): 
        result = tweet.update(self.request.get('text'))

        if result.status_code != '200':
            self.response.out.write(html.header())
            self.response.out.write("tstatus_code: " + str(result.status_code) + "<br>")
            self.response.out.write("content:" + result.content + "<br>")
            self.response.out.write(html.footer())
        else:
            # parser minicloud error
            ret = json.loads(result.content)
            msg = minicloud.parse_error(ret['error']) 
            html.error(msg)


# Sync text from twitter to minicloud
class SyncHandler(webapp.RequestHandler):
    def get(self):
        try:
            tweets = tweet.fetch()
            if isinstance(tweets, dict):
                self.response.out.write(html.error(tweets["error"]))
                return 
            log_flag = False 
            log_msg = '-'
            for twt in tweets:
                # update to minicloud
                result = tweet.update(twt['text'])
                if result.status_code == 200:
                    log_flag = True 
                    log_msg = 'Success'
                else:
                    log_flag = False
                    log_msg = 'Failure'

                # save twitter since id
                appconfig.set_param('twitter_since_id', str(twt['id']))
                # save sync log
                tweet.save(twt['id'], rfc_date(twt['created_at']), twt['text'], log_flag, log_msg)
        except urlfetch.Error, e:
            msg = str(e) + "<br>Your twitter url is: " + appconfig.get_param("twitter_url")
            self.response.out.write(html.error(msg))
            return


        # display sync log
        tweets = tweet.list()
        self.response.out.write(html.header())
        self.response.out.write(html.log(tweets))
        self.response.out.write(html.footer())


# List log
class LogHandler(webapp.RequestHandler):
    def get(self):
        tweets = tweet.list()
        self.response.out.write(html.header())
        self.response.out.write(html.log(tweets))
        self.response.out.write(html.footer())

# Clear log
class ClearHandler(webapp.RequestHandler):
    def get(self):
        tweet.clear()
        tweets = tweet.list()
        self.response.out.write(html.header())
        self.response.out.write(html.log(tweets))
        self.response.out.write(html.footer())

# Not found page
class NullHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(html.header())
        self.response.out.write('Page not found!')
        self.response.out.write(html.footer())

# Print runtime info
class RuntimeHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(html.header())
        self.response.out.write(sys.version + "<br>")
        self.response.out.write(sys.path)
        self.response.out.write("<br>")
        self.response.out.write(html.footer())


# rfc822 ==> datetime
def  rfc_date(str):
    temp = rfc822.parsedate_tz(str)
    stamp = rfc822.mktime_tz(temp)
    return datetime.fromtimestamp(stamp) 


# Web Application
application = webapp.WSGIApplication([
    ('/', IndexHandler),
    ('/loadcfg', LoadConfigHandler),
    ('/savecfg', SaveConfigHandler),
    ('/twitter', TwitterHandler),
    ('/minicloud', MinicloudHandler),
    ('/update', UpdateHandler),
    ('/sync', SyncHandler),
    ('/log', LogHandler),
    ('/clear', ClearHandler),
    ('/rt', RuntimeHandler),
    ('/.*', NullHandler)
    ], debug=True)


def main():
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
